const connection = require("../app/database");

class FriendService {

  // 保存一个用户
  async create(userId, fName, fAvatar, fDesc, fLink) {
    try {
      const statement = `INSERT INTO friend (user_id, f_name, f_avatar, f_desc, f_link) VALUES (?, ?, ?, ?, ?)`;
      const result = await connection.execute(statement, [userId, fName, fAvatar, fDesc, fLink]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一个用户
  async remove(userId, friendId) {
    try {
      const statement = `DELETE FROM friend WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [userId, friendId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 修改一个朋友
  async update(userId, friendId, fName, fAvatar, fDesc, fLink) {
    try {
      const statement = `UPDATE friend SET f_name = ?, f_avatar = ?, f_desc = ?, f_link = ? WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [fName, fAvatar, fDesc, fLink, userId, friendId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取好友详情
  async getFriendById(friendId, userId) {
    try {
      const statement = `SELECT 
                           id 'key', 
                           user_id userId, 
                           f_name name, 
                           f_avatar avatar, 
                           f_desc friendDesc,
                           f_link link,
                           createAt createTime,
                           updateAt updateTime
                         FROM friend WHERE id = ? AND user_id = ?`;
      const [result] = await connection.execute(statement, [friendId, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取朋友列表
  async list(userId) {
    try {
      const statement = `SELECT 
                          id 'key', 
                          user_id userId, 
                          f_name name, 
                          f_avatar avatar, 
                          f_desc friendDesc,
                          f_link link,
                          createAt createTime,
                          updateAt updateTime
                        FROM friend WHERE user_id = ?`;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

}

module.exports = new FriendService();
